﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public static class ListBoxHelper
    {
        /// <summary>
        /// 获取ListBox所有选中的项
        /// </summary>
        /// <param name="inputListBox">ListBox</param>
        /// <returns>返回选中项值的数组</returns>
        public static string[] SelectedValueArr(System.Web.UI.WebControls.ListBox inputListBox)
        {
            //if (inputListBox.Items.Count < 1)
            //{
            //    return new string[]{"err"};
            //}
            IList<string> tStringArr = new List<string>();
            foreach (System.Web.UI.WebControls.ListItem item in inputListBox.Items)
            {
                if (item.Selected == true)
                {
                    tStringArr.Add(item.Value);
                }
            }
            return tStringArr.ToArray();
        }

        /// <summary>
        /// 获取ListBox所有选中的项
        /// </summary>
        /// <param name="inputListBox">ListBox</param>
        /// <returns>返回用,分割的选中项的值</returns>
        public static string SelectedValue(System.Web.UI.WebControls.ListBox inputListBox)
        {
            return String.Join(",", SelectedValueArr(inputListBox));
        }

        /// <summary>
        /// 选中多项指定选项
        /// </summary>
        /// <param name="inputListBox">ListBox</param>
        /// <param name="InputValue">选项列表，用,分割</param>
        public static void SetSelectedValue(System.Web.UI.WebControls.ListBox inputListBox, string InputValue)
        {
            inputListBox.ClearSelection();
            string tString = "," + InputValue + ",";
            foreach (System.Web.UI.WebControls.ListItem item1 in inputListBox.Items)
            {
                if (tString.IndexOf("," + item1.Value + ",") > -1)
                {
                    
                    item1.Selected = true;
                }
            }
        }
    }
}
